package com.example.test.advice.第三章_类_对象_方法.建议48_覆写equals方法必须覆写hashcode方法;

import com.google.common.base.Objects;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashCodeClient {

    public static void main(String[] args) {
        //Person类的实例作为Map的key
        Map<Person,Object> map = new HashMap<Person,Object>(){
            {
                put(new Person("张三"),new Object());
            }
        };
        List<Person> list = new ArrayList<Person>(){
            {
                add(new Person("张三"));
            }
        };

        boolean b1 = list.contains(new Person("张三"));
        boolean b2 = map.containsKey(new Person("张三"));
        System.out.println("b1:"+b1);
        System.out.println("b2:"+b2);
    }
}

class Person{
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        //if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equal(name, person.name);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(name).toHashCode();
    }
}